package com.coldworks.coldjoke;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.coldworks.base.BaseFragment;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.manager.UserManager.UserStateSubject;
import com.coldworks.coldjoke.util.NetworkUtil;
import com.coldworks.coldjoke.util.UrlUtil;

public class NavigationPostJokeFragment extends BaseFragment implements
		Observer {

	private ImageButton menuBtn;
	private ImageButton postBtn;
	private OnMenuShowListener onMenuShowListener;
	private EditText jokeEditText;
	private ProgressDialog progressDialog;
	private PostJokeTask postJokeTask;
	private String jokeContent;
	private boolean isLogin = false;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			onMenuShowListener = (OnMenuShowListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement onMenuShowListener");
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		isLogin = userStateSubject.getUserState() == UserManager.LOGINED ? true
				: false;
		// 获取编辑框焦点
		jokeEditText.setFocusable(true);
		jokeEditText.requestFocus();
		// 打开软键盘
		InputMethodManager imm = (InputMethodManager) getActivity()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		userStateSubject = UserManager.getInstance().getUserStateSubject();
		userStateSubject.addObserver(this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_post_joke, container,
				false);
		jokeEditText = (EditText) view.findViewById(R.id.joke_content);
		menuBtn = (ImageButton) view.findViewById(R.id.button_menu);
		postBtn = (ImageButton) view.findViewById(R.id.button_ok);
		menuBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onMenuShowListener.showMenuNavigation();
			}
		});
		postBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				postJoke();
			}
		});
		return view;
	}

	private UserStateSubject userStateSubject;

	@Override
	public void update(Observable o, Object data) {
		UserStateSubject observable = (UserStateSubject) o;
		if (observable.getUserState() == UserManager.LOGINED) {
			isLogin = true;
			log.info("PostFragment已注册，并被通知到登陆状态");
		} else {
			isLogin = false;
			log.info("PostFragment已注册，并被通知到未登陆状态");
		}
	}

	private void postJoke() {

		if (isLogin) {
			jokeContent = jokeEditText.getText().toString();

			if (jokeContent.length() == 0) {
				Toast.makeText(getActivity(), "一点都不好笑，来点内容嘛！",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (jokeContent.length() < 10) {
				Toast.makeText(getActivity(), "内容太少了，冷不起来嘛！",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (jokeContent.length() > 2000) {
				Toast.makeText(getActivity(), "内容太长了,看完就真的冷冻了！",
						Toast.LENGTH_SHORT).show();
				return;
			} else {
				postJokeTask = new PostJokeTask();
				postJokeTask.execute();
			}
		} else {
			onMenuShowListener.showMenuLogin();
		}

	}

	private class PostJokeTask extends AsyncTask<Void, Integer, Integer> {

		private List<NameValuePair> params;
		private String msg;

		public PostJokeTask() {
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("content", jokeContent));
			params.add(new BasicNameValuePair("type", "text"));
			params.add(new BasicNameValuePair("action", "post_joke"));
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setMessage(getActivity().getResources().getString(
					R.string.publish_posting));
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					PostJokeTask.this.cancel(true);
				}
			});
			progressDialog.show();
		}

		@Override
		protected Integer doInBackground(Void... param) {
			HttpPost httpPost = new HttpPost(UrlUtil.getPostJokeUrl());
			try {
				String sessionId = UserManager.getInstance().getSessionId();
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				httpPost.setHeader("Cookie", "webpy_session_id=" + sessionId);
				HttpResponse httpResponse = BaseNetworkManager.getInstance()
						.createHttpClient(getActivity()).execute(httpPost);
				if (isCancelled()) {
					return BaseCONST.OP.CANCEL;
				}
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					Header contentEncoding = httpResponse
							.getFirstHeader("Content-Encoding");
					JSONObject jsonObject = null;
					if (contentEncoding != null
							&& contentEncoding.getValue().equalsIgnoreCase(
									"gzip")) {
						jsonObject = NetworkUtil.getInstance()
								.getJsonObjectByGzip(
										httpResponse.getEntity().getContent());
					} else {
						jsonObject = NetworkUtil.getInstance().getJSONObject(
								httpResponse.getEntity().getContent());
					}
					if (jsonObject == null) {
						return BaseCONST.OP.ERR_NET;
					}
					if (jsonObject.getString("success").equals("true")) {
						return BaseCONST.OP.SUCC;
					} else {
						msg = jsonObject.getString("error_info");
						return BaseCONST.OP.FAIL;
					}
				} else {
					log.info(String.valueOf(httpResponse.getStatusLine()
							.getStatusCode()));
					return BaseCONST.OP.ERR_NET;
				}
			} catch (ClientProtocolException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (UnsupportedEncodingException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (IOException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (JSONException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			switch (result) {
			case BaseCONST.OP.SUCC:
				Toast.makeText(getActivity(), R.string.publish_post_succ,
						Toast.LENGTH_SHORT).show();
				jokeEditText.getText().clear();
				log.info("succ");
				break;
			case BaseCONST.OP.ERR_NET:
				Toast.makeText(getActivity(), R.string.err_connecting,
						Toast.LENGTH_SHORT).show();
				log.info("error net");
				break;
			case BaseCONST.OP.FAIL:
				Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
				log.info("fail");
				break;
			case BaseCONST.OP.CANCEL:
				log.info("cancelled");
				break;
			}

		}
	}

}
